import plugin from '../../lib/plugins/plugin.js'
import fetch from 'node-fetch'
import lodash from "lodash";
import {segment} from "oicq";

export class example extends plugin {
    constructor () {
        super({
            /** 功能名称 */
            name: '搜图',
            /** 功能描述 */
            dsc: '简单开发示例',
            /** https://oicqjs.github.io/oicq/#events */
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: 5000,
            rule: [
                {
                    /** 命令正则匹配 */
                    reg: '^#搜图(.*)',
                    /** 执行方法 */
                    fnc: 'searchPicture'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^#绑定搜图KEY(.*)',
                    /** 执行方法 */
                    fnc: 'bindKey'
                }
            ]
        })
    }

    /**
     * #一言
     * @param e oicq传递的事件参数e
     */
    async searchPicture (e) {
        /** e.msg 用户的命令消息 */
        logger.info('[用户命令]', e.msg,e)
        let api_key = await redis.get("Yz:searchPicture:mys:api-key");
        if (api_key){
            if (e.img){
                //消息携带图片，则直接搜
                logger.info('[搜图]消息携带图片')
                await this.searchImageAndReply(e.img[0],api_key)
            }else{
                await this.reply(`图来!`)
                //每2秒拉一次群消息记录 查询最近20条 私聊查询5条
                let loopCount = 0;
                let timer = setInterval(async () => {
                    let reply;
                    let currentTime = new Date().getTime();
                    let targetChat;
                    if (this.e.isGroup) {
                        reply = await this.e.group.getChatHistory(false,15);
                        //logger.info(reply.toString())
                        targetChat = reply.filter(function(item){
                            return (item.user_id = e.user_id)
                        })
                    } else {
                        reply = await this.e.friend.getChatHistory(currentTime, 5);
                        targetChat = reply.filter(function(item){
                            return (item.from_id = e.user_id)
                        })
                    }
                    logger.info(targetChat.toString())
                    let lastindex = -1
                    for(let i = (targetChat.length-1);i>=0;i--){
                        //目标最后一次发出指令的索引位置
                        if (targetChat[i].raw_message.indexOf("#搜图")>-1||targetChat[i].raw_message.indexOf("＃搜图")>-1){
                            lastindex = i;
                            break
                        }
                    }
                    logger.info('[搜图]最终指令索引',lastindex)
                    if (lastindex>=0){
                        //从索引后找到第一张图片
                        for(let i = lastindex;i < targetChat.length;i++){
                            //目标最后一次发出指令的索引位置
                            if (targetChat[i].raw_message.indexOf("[图片]")>-1){
                                for (const item of targetChat[i].message) {
                                    if (item.type==="image"){
                                        clearInterval(timer);
                                        return await this.searchImageAndReply(targetChat[i].message[0].url,api_key)
                                    }
                                }
                            }
                        }
                    }
                    loopCount++
                    if (loopCount===10){
                        clearInterval(timer);
                        return this.reply(`等待时间过长，中断对QQ：${e.user_id}的消息响应，如需继续查询请再次发起搜图。`)
                    }
                    //this.searchImageAndReply(e)
                },2000)
            }
            //logger.info('[搜图结果]',res.results);
        }else{
            logger.error('[搜图]未配置API_KEY')
            return await this.reply('未配置saucenao的API_KEY,执行“#绑定搜图KEY + API_KEY”绑定')
        }
    }

    /**
     * #绑定搜图KEY
     * @param e oicq传递的事件参数e
     */
    async bindKey (e) {
        /** e.msg 用户的命令消息 */
        logger.info('[用户命令]', e.msg)
        this.keyWord = this.e.msg
            .trim()
            /** 过滤前缀 */
            .replace(/#|＃|绑定搜图KEY/g, '').trim();
        let redisKey = `Yz:searchPicture:mys:api-key`
        redis.set(redisKey,this.keyWord);
        this.reply('API_KEY设置完成')
    }
    async searchImageAndReply(imgUrl,api_key){
        this.reply(`正在搜图中...`)
        let img =  encodeURIComponent(imgUrl)
        let url = `https://saucenao.com/search.php?url=${img}&db=999&api_key=${api_key}&output_type=2&numres=5&testmode=1`
        logger.info('[搜图请求地址]', url)
        let res = await fetch(url).catch((err) => logger.error(err))
        if (!res){
            logger.error('[搜图] 接口请求失败...')
            return await this.reply('saucenao搜图请求失败...')
        }
        logger.info('[搜图]请求成功')
        res = await res.json()
        let result = [];
        res.results.forEach(item=>{
            let message = ""
            if (item.header.similarity){
                message += `相似度：${item.header.similarity}%\n`
                if (item.data.ext_urls){
                    message += `出处：${item.data.ext_urls.join('\n')}\n`
                }
                if (item.data.title||item.data.jp_name||item.data.eng_name||item.data.source){
                    message += `作品名：${item.data.title||item.data.jp_name||item.data.eng_name||item.data.source}\n`
                }
                if (item.data.creator||item.data.author_name||item.data.author){
                    let author = "";
                    if (item.data.creator===undefined){
                        author = item.data.author_name||item.data.author
                    }else if (typeof item.data.creator === 'string'){
                        author = item.data.creator
                    }else if (typeof item.data.creator === 'object'){
                        author = item.data.creator.join(",")
                    }else{
                        author = "未知"
                    }
                    message += `作者：${author}\n`
                }
                result.push(message)
            }else{
                //忽略没有相似度的结果
            }
        })
        logger.info('[搜图]生成基本消息完成')
        if (result.length===0) {
            logger.info('[搜图]无搜索结果')
            this.reply(`暂无相似搜索结果`)
            return
        }
        result.splice(0,0,"相似度低于50%,则不适合作为参考,请尽量截图单图提高搜索成功率。")
        result.splice(1,0,["原图：\n",segment.image(imgUrl)])
        let forwardMsg = await this.makeForwardMsg(`搜索到的结果`, result)
        await this.reply(forwardMsg)
    }
    async makeForwardMsg (title, msg) {
        let nickname = Bot.nickname
        if (this.e.isGroup) {
            let info = await Bot.getGroupMemberInfo(this.e.group_id, Bot.uin)
            nickname = info.card ?? info.nickname
        }
        let userInfo = {
            user_id: Bot.uin,
            nickname
        }

        let forwardMsg = []

        msg.forEach(item=>{
            forwardMsg.push(
                {
                ...userInfo,
                message: item
            })
        })
        /** 制作转发内容 */
        if (this.e.isGroup) {
            forwardMsg = await this.e.group.makeForwardMsg(forwardMsg)
        } else {
            forwardMsg = await this.e.friend.makeForwardMsg(forwardMsg)
        }

        /** 处理描述 */
        forwardMsg.data = forwardMsg.data
            .replace(/\n/g, '')
            .replace(/<title color="#777777" size="26">(.+?)<\/title>/g, '___')
            .replace(/___+/, `<title color="#777777" size="26">${title}</title>`)

        return forwardMsg
    }
}
